import { useEffect, useState, useRef } from "react";
import { View, DeviceEventEmitter } from "react-native";
import SplashScreen from "react-native-splash-screen";
import NetInfo from "@react-native-community/netinfo";
import { useDispatch } from "react-redux";

import type { EmitterSubscription } from "react-native";

import Router from "@/router";
import { setNetworkState, setNetworkType, setLastNetworkChangeTime } from "@/store/slices/common";
import { getPermissions } from "@/utils";
import { Module } from "@/utils/nativeModules";
import fso from "@/utils/FileOperate/operate";
import cronCheck from "@/utils/cron/check";
import { getFmtTime } from "@/utils/date";
import config from "@/config";
import { testNetInfo } from "@/api/home";

import WidgetProvider from "./WidgetProvider";
import globalMethods from "./GlobalMethodProvider";

// sqlite
import {
  testInitSqlite,
  testCloseSqlite,
  loggerInitSqlite,
  loggerCloseSqlite,
  sliceFileInitSqlite,
  sliceFileCloseSqlite,
  scheduleInitSqlite,
  scheduleCloseSqlite,
  materialInitSqlite,
  materialCloseSqlite
} from "@/sqlite/exports";

// 日志事件
let logLinstener: EmitterSubscription | null = null;

// 初始化配置和数据库
const Provider = () => {
  const [ready, setReady] = useState(false);
  const dispatch = useDispatch();
  const isInit = useRef(false);

  useEffect(() => {
    // 隐藏启动屏页面
    SplashScreen.hide();

    if (isInit.current) return;

    isInit.current = true;

    if (fso.getExternalFilePermission) {
      // 获取文件读写权限
      getPermissions("android.permission.READ_EXTERNAL_STORAGE", "文件读取权限");
      getPermissions("android.permission.WRITE_EXTERNAL_STORAGE", "文件写入权限");
    }

    // 监听网络变化
    const unsubscribe = NetInfo.addEventListener(state => {
      // 当前的网络类型
      dispatch(setNetworkType(state.type));
      dispatch(setLastNetworkChangeTime(getFmtTime()));

      // 因为是在内网, 当前是否在线调用接口去判断是否在线
      // testNetInfo()
      //   .then(res => {
      //     dispatch(setNetworkState(Boolean(res)));
      //   })
      //   .catch(err => {
      //     dispatch(setNetworkState(false));
      //   });
    });

    // 原生端事件
    if (config.IS_DEBUG) {
      // log 记录
      logLinstener = DeviceEventEmitter.addListener(Module.LOG_EVENT_KEY, (msg: any) => {
        console.log(`[Java LOG] ${new Date().toLocaleTimeString()}: `, JSON.stringify(msg));

        globalMethods.$showMessage({
          type: "toast",
          message: JSON.stringify(msg)
        });
      });
    }

    // 初始化文件操作
    fso
      .init()
      .then(() => {
        console.log("目录初始化成功, 基础目录: ", fso.baseDir);
        // if (config.IS_DEBUG) {
        //   console.warn("开发环境下每次启动都清空当天的日志");
        //   fso.clearTodayFile();
        // }
      })
      .catch(err => {
        console.log("目录初始化失败: ", err);
      })
      .finally(() => {
        cronCheck();
      });

    Promise.all([
      testInitSqlite(), // 测试sqlite
      loggerInitSqlite(), // 日志sqlite
      sliceFileInitSqlite(), // 文件分片下载sqlite
      scheduleInitSqlite(), // 排期sqlite
      materialInitSqlite() // 素材sqlite
    ])
      .then(() => {
        fso.info("sqlite初始化成功");
      })
      .catch(err => {
        fso.error("sqlite初始化失败: ", err);
      })
      .finally(() => {
        console.groupEnd();
        setReady(true);
      });

    return () => {
      console.log("全局卸载");

      unsubscribe();

      if (logLinstener) {
        logLinstener.remove();
        logLinstener = null;
      }

      // TODO 这里不能关闭数据库, 不然会导致后续无法初始化成功
      // testCloseSqlite();
      // loggerCloseSqlite();
      // sliceFileCloseSqlite();
      // scheduleCloseSqlite();
      // materialCloseSqlite();
      // exeCmdCloseSqlite();
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <View style={{ width: "100%", height: "100%" }}>
      {/* 路由页面 */}
      {ready && <Router />}

      <WidgetProvider />
    </View>
  );
};

export default Provider;
